package cn.i7baozh.boot.learn.initializer.processor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangbaoqi532
 * @date 2025/2/19
 */
@Slf4j
public class MyPropertyProcessor implements BeanFactoryPostProcessor {

    private ConfigurableEnvironment configurableEnvironment;

    //通过构造函数拿到环境
    public MyPropertyProcessor(ConfigurableEnvironment environment) {
        this.configurableEnvironment = environment;
    }

    /**
     * spring会在所有环境都准备好后再执行到这里
     * @param beanFactory
     * @throws BeansException
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        MutablePropertySources propertySources = configurableEnvironment.getPropertySources();

        //通过下面这些代码可以在启动的时候更改一些配置， 例如对远程密文解密
        //也可以将自己的一些特殊化配置加到环境中去
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof OriginTrackedMapPropertySource prop) {
                Map<String, Object> source = prop.getSource();
                log.info("source {}", source);
            }
        }

        //自定义一些配置进去
        Map<String, Object> custom = new HashMap<>();
        custom.put("dynamic.value", "postProcess过程修改了");
        OriginTrackedMapPropertySource myCustomPropertySource = new OriginTrackedMapPropertySource("custom",custom
                );
        //addFirst 优先级最高 addLast优先级最低可能被别的配置覆盖了
        propertySources.addFirst(myCustomPropertySource);
    }
}
